//
//  ProductOrdersView.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/5/6.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "ProductOrdersView.h"

#import "ProductOrdersListCell.h"

#import "ProductOrderListModel.h"

#import "ProductOrderDetailViewController.h"

#import "ProductOrderModel.h"

#import "ProductOrderItemCell.h"

#import "OrderParticularsViewController.h"

#import "OrderEvaluationViewController.h"//评价

#import "OrderApplyRefundView.h"//申请退换货view

@interface ProductOrdersView()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,assign) NSInteger sourceType;

@property (nonatomic,assign) NSInteger currentPage;

@property (nonatomic,strong) NSMutableArray *dataSourceArr;

@end

@implementation ProductOrdersView

- (instancetype)initWithFrame:(CGRect)frame withSourceType:(NSInteger)sourceType{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = MainBackColor;
        self.dataSourceArr = [NSMutableArray array];
        self.sourceType = sourceType;
        self.currentPage = 1;
        [self initUI];
        [self getNewData];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultClick:) name:@"wechatPayResultNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultClick:) name:@"wechatPayResultNotificationSuccess" object:nil];
    }
    return self;
}
#pragma mark - noti
-(void)payResultClick:(NSNotification *)noti{
    NSDictionary *dic = (NSDictionary *)noti.userInfo;
    if ([dic[@"payStatus"] intValue] == 0) {
        [[XNProgressHUD shared] showSuccessWithTitle:@"支付成功!"];
        [self.tableView reloadData];
    }else{
        [[XNProgressHUD shared] showErrorWithTitle:dic[@"payResult"]];
    }
}
#pragma mark - data
-(void)getNewData{
    self.dataSourceArr = [NSMutableArray array];
    if (self.sourceType > 3) {
        [NetWorkingOrder getProductItemListWithStatus:self.sourceType-3 withPage:self.currentPage withSuccessBlock:^(id  _Nonnull responseObj) {
            [self.tableView.mj_header endRefreshing];
            NSDictionary *data = responseObj[@"data"];
            NSArray *records = data[@"records"];
            for (NSDictionary *dic in records) {
                ProductOrderModel *model = [ProductOrderModel paraWithDict:dic];
                [self.dataSourceArr addObject:model];
            }
            [self.tableView reloadData];
        }];
    }else{
        [NetWorkingOrder getProductOrdersListWithStatus:self.sourceType withPage:self.currentPage withSuccessBlock:^(id  _Nonnull responseObj) {
            [self.tableView.mj_header endRefreshing];
            NSDictionary *data = responseObj[@"data"];
            NSArray *records = data[@"records"];
            for (NSDictionary *dic in records) {
                ProductOrderListModel *model = [ProductOrderListModel paraWithDict:dic];
                [self.dataSourceArr addObject:model];
            }
            [self.tableView reloadData];
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}
-(void)getMoreData{
    if (self.sourceType > 3) {
        [NetWorkingOrder getProductItemListWithStatus:self.sourceType-3 withPage:self.currentPage withSuccessBlock:^(id  _Nonnull responseObj) {
            [self.tableView.mj_footer endRefreshing];
            NSDictionary *data = responseObj[@"data"];
            NSArray *records = data[@"records"];
            for (NSDictionary *dic in records) {
                ProductOrderModel *model = [ProductOrderModel paraWithDict:dic];
                [self.dataSourceArr addObject:model];
            }
            [self.tableView reloadData];
        }];
    }else{
        [NetWorkingOrder getProductOrdersListWithStatus:self.sourceType withPage:self.currentPage withSuccessBlock:^(id  _Nonnull responseObj) {
            [self.tableView.mj_footer endRefreshing];
            NSDictionary *data = responseObj[@"data"];
            NSArray *records = data[@"records"];
            for (NSDictionary *dic in records) {
                ProductOrderListModel *model = [ProductOrderListModel paraWithDict:dic];
                [self.dataSourceArr addObject:model];
            }
            [self.tableView reloadData];
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_footer endRefreshing];
    });
}
#pragma mark - UI
-(void)initUI{
    [self addSubview:self.tableView];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.currentPage = 1;
        [self getNewData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.currentPage = self.currentPage + 1;
        [self.tableView.mj_footer beginRefreshing];
        [self getMoreData];
    }];
}
#pragma mark - lazy
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, self.height) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.backgroundColor = MainBackColor;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1f)];
        [_tableView setTableHeaderView:view];
    }
    return _tableView;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.sourceType>3) {
        return 282;
    }
    ProductOrderListModel *model = self.dataSourceArr[indexPath.row];
    return model.cellHeight;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.sourceType > 3) {
        ProductOrderItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductOrderItemCell"];
        if (!cell) {
            cell = [[ProductOrderItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ProductOrderItemCell"];
        }
        cell.model = self.dataSourceArr[indexPath.row];
        [cell setTouchBlock:^(ProductOrderModel * _Nonnull orderModel, NSString * _Nonnull touchTitle) {
            [self orderParticularsTouchClick:orderModel withTouchTitle:touchTitle];
        }];
        return cell;
    }else{
        NSString *cellID = [NSString stringWithFormat:@"ProductOrdersListCell/%ld/%ld",indexPath.section,indexPath.row];
        ProductOrdersListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[ProductOrdersListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        cell.model = self.dataSourceArr[indexPath.row];
        [cell setTouchBlock:^(ProductOrderListModel * _Nonnull orderModel, NSString * _Nonnull touchTitle) {
            [self orderDetailTouchClick:orderModel withTouchTitle:touchTitle];
        }];
        return cell;
    }
}
//点击事件
-(void)orderDetailTouchClick:(ProductOrderListModel *)model withTouchTitle:(NSString *)touchTitle{
    if ([touchTitle isEqualToString:@"查看详情"]) {
        [self toDetailClick:model];
    }else if ([touchTitle isEqualToString:@"去支付"]){
        [self payWithOrderNo:model.orderno];
    }else if ([touchTitle isEqualToString:@"取消订单"]){
        [OrderManager cancelOrderWithOrderNo:model.orderno withSuccessBlock:^{
            [self getNewData];
        }];
    }else if ([touchTitle isEqualToString:@"确认收货"]){
        [OrderManager confirmTheGoodsWithOrderNo:model.orderno withSuccessBlock:^{
            [self getNewData];
            [self popAndPostRefreshNotificationWithListType:4];
        }];
    }else if ([touchTitle isEqualToString:@"查看物流"]){
//        [self checkTheLogistics];     TODO
    }else if ([touchTitle isEqualToString:@"删除订单"]){
        [OrderManager deleteOrderWithOrderNo:model.orderno withSuccessBlock:^{
            [self getNewData];
        }];
    }else if ([touchTitle isEqualToString:@"确认完成"]){
        [self confrimDoneWithID:[NSString stringWithFormat:@"%ld",(long)model.ID]];
    }
}
//点击事件
-(void)orderParticularsTouchClick:(ProductOrderModel *)model withTouchTitle:(NSString *)touchTitle{
    if ([touchTitle isEqualToString:@"查看详情"]) {
        [self toOrderParticulars:model];
    }else if ([touchTitle isEqualToString:@"取消订单"]){
        [OrderManager cancelOrderWithOrderNo:model.orderno withSuccessBlock:^{
            [self getNewData];
            [self popAndPostRefreshNotificationWithListType:5];
        }];
    }else if ([touchTitle isEqualToString:@"确认收货"]){
        [OrderManager confirmTheGoodsWithOrderNo:model.orderno withSuccessBlock:^{
            [self getNewData];
            [self popAndPostRefreshNotificationWithListType:4];
        }];
    }else if ([touchTitle isEqualToString:@"查看物流"]){
//        [self checkTheLogistics];  TODO
    }else if ([touchTitle isEqualToString:@"删除订单"]){
        [OrderManager deleteOrderWithOrderNo:model.orderno withSuccessBlock:^{
            [self getNewData];
        }];
    }else if ([touchTitle isEqualToString:@"确认完成"]){
        [self confrimDoneWithID:[NSString stringWithFormat:@"%ld",(long)model.ID]];
    }else if ([touchTitle isEqualToString:@"去评价"]){
        [self toEvaluationWithItemId:[NSString stringWithFormat:@"%ld",model.ID] withGoodsName:model.name withGoodsImg:model.picture];
    }else if ([touchTitle isEqualToString:@"申请退换货"]) {
        [self applyRefundWithType:0 withItemId:model.ID];
    }else if ([touchTitle isEqualToString:@"申请退款"]) {
        [self applyRefundWithType:1 withItemId:model.ID];
    }
}
//订单详情
-(void)toDetailClick:(ProductOrderListModel *)model{
    ProductOrderDetailViewController *vc = [[ProductOrderDetailViewController alloc] init];
    vc.orderModel = model;
    vc.sourceType = self.sourceType;
    [[Configuration getCurrentVC].navigationController pushViewController:vc animated:YES];
}
//订单明细详情
-(void)toOrderParticulars:(ProductOrderModel *)model{
    OrderParticularsViewController *vc = [[OrderParticularsViewController alloc] init];
    vc.orderModel = model;
    vc.sourceType = self.sourceType;
    [[Configuration getCurrentVC].navigationController pushViewController:vc animated:YES];
}
//去评价
-(void)toEvaluationWithItemId:(NSString *)itemID withGoodsName:(NSString *)goodsName withGoodsImg:(NSString *)pictrue{
    OrderEvaluationViewController *vc = [[OrderEvaluationViewController alloc] init];
    vc.itemID = itemID;
    vc.goodsName = goodsName;
    vc.goodsLogo = pictrue;
    [[Configuration getCurrentVC].navigationController pushViewController:vc animated:YES];
}
//确认完成
-(void)confrimDoneWithID:(NSString *)itemID{
    [OrderManager confrimDoneWithID:itemID withSuccessBlock:^{
        [self getNewData];
        [self popAndPostRefreshNotificationWithListType:4];
    }];
}
//去支付
-(void)payWithOrderNo:(NSString *)orderNo{
    [[XNProgressHUD shared] showLoadingWithTitle:@"正在支付..."];
    [OrderManager payWithOrderNo:orderNo withSuccessBlock:^{
        [self getNewData];
        [self popAndPostRefreshNotificationWithListType:2];
    } withPayBlock:^(id  _Nonnull payResponseDict) {
        //拉起支付
        NSDictionary *dict = (NSDictionary *)payResponseDict;
        [WechatPayManager handleWechatPayWithPayDic:dict];
    }];
}
//申请退换货
-(void)applyRefundWithType:(NSInteger)type withItemId:(NSInteger)itemID{
    WEAKSELF(self);
    OrderApplyRefundView *refundView = [[OrderApplyRefundView alloc] initWithTitle:(type == 0?@"申请退换货":@"申请退款")];
    [refundView show];
    NSString *itemId = [NSString stringWithFormat:@"%ld",(long)itemID];
    [refundView setRefundBlock:^(NSString * _Nonnull refundReason) {
        if (type == 0) {
            [NetWorkingOrder applyOrderReject:itemId note:refundReason withSuccessBlock:^(id  _Nonnull responseObj) {
                [[XNProgressHUD shared] showSuccessWithTitle:@"已为您申请退换货!"];
                [self getNewData];
                [self popAndPostRefreshNotificationWithListType:5];
            }];
        }else{
            [NetWorkingOrder applyOrderRefund:itemId note:refundReason withSuccessBlock:^(id  _Nonnull responseObj) {
                [[XNProgressHUD shared] showSuccessWithTitle:@"已为您申请退款!"];
                [self getNewData];
                [self popAndPostRefreshNotificationWithListType:5];
            }];
        }
    }];
}

//发送通知让订单列表刷新 并跳转相关页面
-(void)popAndPostRefreshNotificationWithListType:(NSInteger)listType{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSDictionary *dic = @{@"listType":@(listType)};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListNotification" object:nil userInfo:dic];
    });
}

@end


